<?php


namespace app\common\business;


use app\common\lib\Str;
use app\common\lib\Time;
use think\Exception;
use think\facade\Cache;

class User extends BusBase
{
    protected $model = null;

    public function __construct()
    {
        $this->model = new \app\common\model\mysql\User();
    }


    public function login($data)
    {

        $code = Cache::get('code_' . $data['phone_number']);

//        if (empty($code) || $code != $data['code']) {
//            throw new Exception('不存在该验证码');
//        }

        $user = $this->model->getAdminUserByPhone($data['phone_number']);


        if (!$user) {
            return false;
        }

        $token = Str::getToken($data['phone_number']);

        $redis_data = [
            'id' => $user->id,
            'username' => $user->username,
        ];

        return Cache::store('redis')->set('token_' . $token, $redis_data, Time::userLoginExpiresTime($data['type'])) ? ['token' => $token, 'username' => $user->username] : false;
    }


    public function getNormalUserById($id)
    {
        $user = $this->model->getUserById($id);
        if (!$user || $user->status != 1) {
            return [];
        }

        return $user->toArray();
    }

    public function getUserByUsername($username)
    {
        $user = $this->model->getUserByUsername($username);
        if (!$user || $user->status != 1) {
            return [];
        }

        return $user->toArray();
    }


    public function update($id, $data, $token)
    {
        $user = $this->getNormalUserById($id);

        if (!$user) {
            throw new Exception('用户不存在');
        }

        $user = $this->getUserByUsername($data['username']);

        if ($user && $user['id'] != $id) {
            throw new Exception('该用户已经存在');
        }

        $this->model->updateById($id, $data);

//        if (!$this->user->updateById($id, $data)) {
//            throw new Exception('修改用户异常');
//        }
        try {

            $redis_data = [
                'id' => $id,
                'username' => $data['username']
            ];
            Cache::store('redis')->set('token_' . $token, $redis_data);
        } catch (Exception $e) {
            throw  new Exception('redis更新失败');
        }

        return true;
    }
}